package org.scboy.common.dynamic.node.entityNode;

import java.util.Calendar;
import java.util.Date;

import org.scboy.common.annotation.ScriptNode;
import org.scboy.common.dynamic.node.BaseNode;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;


@ScriptNode("DATETIME_CREATE")
public class DateTimeNode extends BaseNode {
	
	/**
	 * 格式化字符串
	 */
	private String format="";
	
	@Override
	public Object run() {
		
		/**
		 * 测试日志
		 */
		if(this.script.isTest()) {
			this.script.appendMsg("----->开始执行："+getNodeName()+" 节点ID："+this.getId());
		}
		
		/**
		 * 流出节点
		 */
		BaseNode runTo = getRunTo("to");
		
		/**
		 * 生成当前时间
		 */
		Calendar calendar=Calendar.getInstance();
		
		/**
		 * 获取时间
		 */
		Date time=getSourceData("datetime", false, Date.class);
		if(time!=null) {
			calendar.setTime(time);
		}
		
		/**
		 * 设置输出值缓存
		 */
		this.setData("datetime", calendar.getTime());
		this.setData("long", calendar.getTime().getTime());
		this.setData("year", calendar.get(Calendar.YEAR));
		this.setData("month", calendar.get(Calendar.MONTH)+1);
		this.setData("day", calendar.get(Calendar.DAY_OF_MONTH));
		this.setData("hour", calendar.get(Calendar.HOUR_OF_DAY));
		this.setData("minute", calendar.get(Calendar.MINUTE));
		this.setData("second", calendar.get(Calendar.SECOND));
		this.setData("format", DateUtil.format(calendar.getTime(), format));
		
		/**
		 * 测试日志
		 */
		if(this.script.isTest()) {
			this.script.appendMsg("缓存数据：\r\n"+entityToString(this.getDataAll()));
			this.script.appendMsg("执行下个节点："+runTo.getNodeName()+" 节点ID："+runTo.getId());
		}
		//执行下个节点
		return runTo.run();
	}

	@Override
	public void create(JSONObject object) {
		format=object.getStr("format");
		if(StrUtil.isEmpty(format)) {
			format="yyyy-MM-dd HH:mm:ss";
		}
	}
}
